#include "livemodel.h"
#include <algorithm>

namespace yc {

LiveModel::LiveModel(QObject* parent) : QObject { parent } { }

LiveModel::~LiveModel()
{
    qDeleteAll(lives_);
    lives_.clear();
}

LiveWebEntry LiveModel::webEntry(int platform) const
{
    for (const auto& i : std::as_const(web_entries_)) {
        if (i.platform == platform) {
            return i;
        }
    }
    return LiveWebEntry {};
}

LiveInfo* LiveModel::live(int id) const
{
    for (LiveInfo* p : std::as_const(lives_)) {
        if (p->id == id) {
            return p;
        }
    }
    return nullptr;
}

void LiveModel::add(const LiveInfo& li)
{
    if (auto p = live(li.id)) {
        *p = li;
        Q_EMIT changed(p, QPrivateSignal());
    } else {
        p = new LiveInfo { li };
        lives_.push_back(p);
        Q_EMIT added(p, QPrivateSignal());
    }
}

void LiveModel::remove(int id)
{
    auto it = std::find_if(lives_.constBegin(), lives_.constEnd(),
                           [id](LiveInfo* li) { return id == li->id; });
    if (it != lives_.constEnd()) {
        auto p = *it;
        lives_.erase(it);
        Q_EMIT removed(p, QPrivateSignal());
        delete p;
    }
}

void LiveModel::clear()
{
    if (!lives_.empty()) {
        Q_EMIT modelAboutToBeReset(QPrivateSignal());
        qDeleteAll(lives_);
        lives_.clear();
        Q_EMIT modelReset(QPrivateSignal());
    }
}

LiveInfo* LiveModel::activeLive(int presenter) const
{
    auto it = std::find_if(lives_.constBegin(), lives_.constEnd(),
                           [presenter](LiveInfo* li) { return presenter == li->presenter; });
    return it != lives_.constEnd() ? *it : nullptr;
}

LiveInfo* LiveModel::findLive(const QString& platform_id) const
{
    auto it = std::find_if(lives_.constBegin(), lives_.constEnd(),
                           [platform_id](LiveInfo* li) { return platform_id == li->platform_id; });
    return it != lives_.constEnd() ? *it : nullptr;
}

void LiveModel::setLiveStatus(int id, int status, int view_count, int like_count,
                              const QDateTime& update_time, int updater)
{
    if (auto p = live(id)) {
        setLiveStatus(p, status, view_count, like_count, update_time, updater);
    }
}

void LiveModel::setLiveStatus(LiveInfo* li, int status, int view_count, int like_count,
                              const QDateTime& update_time, int updater)
{
    if (li) {
        li->update_time = update_time;
        li->updater = updater;
        if (li->status != status || li->view_count != view_count || li->like_count != like_count) {
            li->status = status;
            li->view_count = view_count;
            li->like_count = like_count;
            Q_EMIT changed(li, QPrivateSignal());
        }
    }
}

} // namespace yc
